Upload Hyper-V VMs backups to Storage Blob

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Import-Module PS-Pushover

$VMnames = 'server01', 'server02', 'server03' # VMs to backup
$Export = 'S:\_Export' # Staging directory
$AzureBlob = '' # Azure Blog SAS
$PushoverToken = ''
$PushoverUser = ''

#Setup Notification channel
$context = 'Backup to Azure Blob'
Set-PushoverSession -token $PushoverToken -user $PushoverUser

Get-ChildItem -Path $Export -Directory  | Remove-Item -Force -Recurse

ForEach ($VMname in $VMnames)
{
  ## Do a regular export of the VMs.
  $VM = Get-VM -Name $VMname
  Export-VM -VM $VM -Path "$Export"
  $folderSize = "{0:N2} MB" -f ((Get-ChildItem "$Export\$VMname" -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB)

  ## Rename the VM folder
  Get-ChildItem -Path $Export -Filter $VMname -Directory | Rename-Item -NewName ("$Export\$VMname-{0:yyyy-MM-dd-HH-mm-ss}" -f (Get-Date))

  #Copy to Azure Backup
  C:\_sources\azcopy.exe cp $Export $AzureBlob --recursive=true

  if($?)
  {
    Send-PushoverMessage -title $context -message "Backed up server $VMname - $folderSize"
  }
  else { Send-PushoverMessage -title $context -message "Failed backing up server $VMname" }

  Get-ChildItem -Path $Export -Directory  | Remove-Item -Force -Recurse
}